<?php defined('BASEPATH') || exit('No direct script access allowed');

class Buildings_model extends BF_Model
{
    protected $table_name	= 'building';
	protected $key			= 'id';
	protected $date_format	= 'datetime';

	protected $log_user 	= false;
    protected $set_created	= false;//true;
	protected $set_modified = false;//true;
	protected $soft_deletes	= true;

	protected $created_field     = 'created_on';
	protected $modified_field    = 'modified_on';
    protected $deleted_field     = 'deleted';

	// Customize the operations of the model without recreating the insert,
    // update, etc. methods by adding the method names to act as callbacks here.
	protected $before_insert 	= array();
	protected $after_insert 	= array();
	protected $before_update 	= array();
	protected $after_update 	= array();
	protected $before_find 	    = array();
	protected $after_find 		= array('set_common');
	protected $before_delete 	= array();
	protected $after_delete 	= array();

	// For performance reasons, you may require your model to NOT return the id
	// of the last inserted row as it is a bit of a slow method. This is
    // primarily helpful when running big loops over data.
	protected $return_insert_id = true;

	// The default type for returned row data.
	protected $return_type = 'object';

	// Items that are always removed from data prior to inserts or updates.
	protected $protected_attributes = array();

	// You may need to move certain rules (like required) into the
	// $insert_validation_rules array and out of the standard validation array.
	// That way it is only required during inserts, not updates which may only
	// be updating a portion of the data.
	protected $validation_rules 		= array(
		array(
			'field' => 'developer_id',
			'label' => 'lang:buildings_field_developer_id',
			'rules' => 'max_length[11]',
		),
		array(
			'field' => 'name',
			'label' => 'lang:buildings_field_name',
			'rules' => 'required|trim|max_length[100]',
		),
		array(
			'field' => 'code',
			'label' => 'lang:buildings_field_code',
			'rules' => 'required|unique[bf_building.code,bf_building.id]|trim|max_length[20]',
		),
		array(
			'field' => 'ave_price',
			'label' => 'lang:buildings_field_ave_price',
			'rules' => 'trim|max_length[8]',
		),
		array(
			'field' => 'status',
			'label' => 'lang:buildings_field_status',
			'rules' => 'max_length[1]',
		),
		array(
			'field' => 'open_time',
			'label' => 'lang:buildings_field_open_time',
			'rules' => 'trim|max_length[20]',
		),
		array(
			'field' => 'pass_time',
			'label' => 'lang:buildings_field_pass_time',
			'rules' => 'trim|max_length[20]',
		),
	);
	protected $insert_validation_rules  = array();
	protected $skip_validation 			= true;

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function prep_data($post_data) {
        $data = parent::prep_data($post_data);
        $data['ave_price'] = $post_data['ave_price'] ? : 0;

        return $data;
    }

    protected function set_common($row) {
        if (is_object($row)) {
            if (is_fang90_server_name()) {
                // fang90 域名处理
                $row->telephone = 4006812598;
            }
            if (is_plusfang_server_name()) {
                // plus-fang 域名处理
                // $row->telephone = 4006812598;
            }
        }
        return $row;
    }

    /**
     * 获取全部楼盘
     * @param  int $deleted
     * @return mixed            数组或者false或者空
     */
    public function buildings($deleted = 0) {
    	$this->db->where(array('deleted'=>$deleted));
    	return $this->find_all();
    }

    /**
     * 通过ID获取楼盘
     * @param  int $id 楼盘ID
     * @return mixed     数组或者false
     */
    public function getBuildingById($id) {
    	if (empty($id)) return false;
    	$building = $this->find($id);
    	return $building;
    }

    /**
     * 通过code获取楼盘
     * @param  string $code 楼盘code
     * @return mixed     数组或者false
     */
    public function getBuildingByCode($code) {
    	if (empty($code)) return false;
    	$building = $this->find_by(array('code'=>$code));
    	return $building;
    }

    /**
     * 获取楼盘图片
     * @param  int $buildingId 楼盘ID
     * @return mixed           数组或者false
     */
    public function getBuildingPhotos($buildingId) {
        if (empty($buildingId)) return false;
        $this->load->model('buildings/photos_model');
        $photos = $this->photos_model->getPhotosByBuildingId($buildingId);
        if (is_array($photos)) {
            // 增加处理多个域名下的图片
            $data = [];
            $hasFang90 = false;
            foreach ($photos as $val) {
                $domain = $val->domain ? : 'udfang';
                $subTypeCode = building_photo_subtype_code()[$val->sub_type];
                $platformCode = building_photo_platform_code()[$val->platform];
                $data[$domain][$subTypeCode][$platformCode][] = $val;
                if ($domain == 'fang90') $hasFang90 = true;
            }
            $data = ($hasFang90 && is_fang90_server_name()) ? array_merge($data['udfang'], $data['fang90']) : $data['udfang'];
            return $data;
            // 增加处理多个域名下的图片 -- 结束

            // 以后如果不需要处理多个域名的图片，可删除上面的代码，使用下面的代码
        	// $data = [];
        	// foreach ($photos as $val) {
        	// 	$subTypeCode = building_photo_subtype_code()[$val->sub_type];
        	// 	$platformCode = building_photo_platform_code()[$val->platform];
        	// 	$data[$subTypeCode][$platformCode][] = $val;
        	// }
        	return $data;
        }
        return false;
    }

    /**
     * 获取楼盘户型图片
     * @param  int $buildingId 楼盘ID
     * @return mixed           数组或者false
     */
    public function getHuXingBuildingPhotos($buildingId,$targetSubId) {
        if (empty($buildingId)) return false;
       
        $huXingPhotos = $this->photos_model->getHuXingPhotosBy($buildingId,$targetSubId,$type = 1);
         if (is_array($huXingPhotos)) {
            $info = [];
            foreach ($huXingPhotos as $val) {
                $platformCode = building_photo_platform_code()[$val->platform];
                $info[$platformCode][] = $val;
            }
            return $info;
         }

        return false;
    }

    /**
     * 通过楼盘ID获取相关楼盘
     * @param  int $buildingId 楼盘ID
     * @return mixed           数组或者false
     */
    public function getRelatedItemsById($buildingId) {
        if (empty($buildingId)) return false;
        $this->load->model('area/area_model');
        // 区域、均价
        $building = $this->getBuildingById($buildingId);

        $step = $building->ave_price > 20000 ? 1000 : 3000;
        $whereAlive = "deleted = 0 AND publish = 1";
        // 均价条件
        // $wherePrice = "ave_price > ".($building->ave_price - $step)." AND ave_price < ".($building->ave_price + $step);
        // 区域条件
        $whereArea = "city_id = {$building->city_id}";
        $where = "{$whereAlive} AND {$whereArea} AND id != {$building->id}";
        $buildings = $this->where($where)->find_all();

        // if (!is_array($buildings)) {
        //     // 只查区域条件楼盘
        //     $where = "{$whereAlive} AND {$whereArea} AND id != {$building->id}";
        //     $buildings = $this->where($where)->limit(8, 0)->find_all();
        // }

        // if (!is_array($buildings) || count($buildings) < 4) {
        //     // 查其他楼盘
        //     $where = "{$whereAlive} AND id != {$building->id}";
        //     $buildings = $this->where($where)->limit(rand(4,8), 0)->find_all();
        // }

        if (is_array($buildings)) {
            //$buildings = $this->onlineBuildings($buildings);
        }

        // 没有楼盘重复本身
        if (!is_array($buildings)) $buildings[] = $building;
        if (is_array($buildings)) {
            // 取楼盘封面图
            $this->load->model('buildings/photos_model');
            foreach ($buildings as $key => $val) {
                $photo = $this->photos_model->getCoverPhotoByBuildingId($val->id);
                $buildings[$key]->cover_absolute_url = $photo->absolute_url;
                // 取城市
                $city = $this->area_model->find($val->city_id);
                $buildings[$key]->city = $city;
                // 取tag
                $tags = $this->buildingstag_model->tags($val->id);
                $buildings[$key]->tag = $tags;
                // 价格格式化
                $buildings[$key]->ave_price = number_format($val->ave_price);
            }
        }

        return $buildings;
    }

    public function onlineBuildings($buildings) {
        // 获取在投楼盘数据
        $key = 'online_buildings';
        $this->load->driver('cache');
        $onlineBuildings = $this->cache->redis->get($key);
        if (!is_array($onlineBuildings)) {
            // 缓存数据不存在，通过接口获取数据
            $url = 'http://120.26.112.32:8080/dms/onlineBuilding';
            $this->load->library('curl', $url);
            $returnStr = $this->curl->execute();
            if (empty($returnStr)) return $buildings;
            $obj = json_decode($returnStr);
            if ($obj->status == 'success') {
                $onlineBuildings = $obj->data;
                $this->cache->redis->save($key, $onlineBuildings, 60*30);
            } else {
                return $buildings;
            }
        }

        $data = [];
        foreach ($buildings as $key => $val) {
            foreach ($onlineBuildings as $v) {
                if ($val->code == $v) $data[] = $val;
            }
        }
        return $data;
    }

    /**
     * 获取灵溪项目
     * @return mixed  数组或者false
     * @author zephan <zephanliu@gmail.com>
     */
    public function lingxiBuildings() {
        $this->load->model('buildings/buildingsinfo_model');
        $infoTable = $this->buildingsinfo_model->get_table();
        $this->db->select("{$this->table_name}.id, {$this->table_name}.name, {$this->table_name}.code")->where("{$this->table_name}.deleted = 0 AND {$infoTable}.lingxi_switch = 1")->join($infoTable, "{$this->table_name}.id = {$infoTable}.building_id");
        return $this->find_all();
    }
    /**
     * 爬虫库到楼盘表数据格式化
     * @return mixed  数组或者false
     */
    public function handleDataFromSpider($buildingInfo){

        if(empty($buildingInfo)) return false;
        $buildingExistData = $this->find_by(array('dmp_building_code'=>$buildingInfo['dmp_building_code'], 'deleted'=>0));
        if($buildingExistData) return ['id'=>$buildingExistData->id, 'code'=>$buildingExistData->code];
        //楼盘名转拼音
        $this->load->library('pinyin/pinyin');
        $code = $this->pinyin->ChineseToPinyin($buildingInfo['building_name'], false, true);
        $codeExist = $this->find_by(array('code'=>$code));//验证是否code已存在
        if($codeExist){$code = $code."udf";}
        
        $building_data = array(
                'name'=>$buildingInfo['building_name'],
                'code'=>$code,
                'dmp_building_code'=>$buildingInfo['dmp_building_code'],
                "ave_price"=>is_numeric($buildingInfo['price']) ? $buildingInfo['price'] : 0,

            );
        $returnId = $this->insert($building_data);
        if($returnId){
            // 更新building_info表
            $year = 0;
            if (!empty($buildingInfo['right_year'])) {
                if (strpos($buildingInfo['right_year'], '70') === true) {
                    $year = 70;
                } else if (strpos($buildingInfo['right_year'], '50') === true) {
                    $year = 50;
                } else if (strpos($buildingInfo['right_year'], '40') === true) {
                    $year = 40;
                }
            }
            $info_data = array(
                    'building_id'=>$returnId,
                    'address'=>!empty($buildingInfo['building_address']) ? $buildingInfo['building_address'] : "",
                    'sale_address'=>!empty($buildingInfo['sales_address']) ? $buildingInfo['sales_address'] : "",
                    'floor_space'=>!empty($buildingInfo['land_area']) ? intval($buildingInfo['land_area']) : 0,
                    'all_space'=>!empty($buildingInfo['build_area']) ? intval($buildingInfo['build_area']) : 0,
                    'rongji_lv'=>!empty($buildingInfo['floor_rate']) ? intval($buildingInfo['floor_rate']) : "",
                    'lvhua_lv'=>!empty($buildingInfo['green_rate']) ? str_replace('%', '', $buildingInfo['green_rate']) : "",
                    'chanquan_n'=>$year,
                    'zhuangxiu_qk'=>!empty($buildingInfo['renovate_type']) ? $buildingInfo['renovate_type'] : "",
                    'property_type'=>!empty($buildingInfo['property_type']) ? $buildingInfo['property_type'] : "",
                    'wuye_gs'=>!empty($buildingInfo['property_company']) ? $buildingInfo['property_company'] : "",
                    'wuye_fei'=>!empty($buildingInfo['property_price']) ? $buildingInfo['property_price'] : "",
                    'price_desc'=>!empty($buildingInfo['price']) ? $buildingInfo['price'] : "",
                    'phone_switch'=>0,
                    'hx_switch'=>0,
                    'seo_title'=>"{$buildingInfo['building_name']} - U点房",
                    'seo_keywords'=>"{$buildingInfo['building_name']}, 新开楼盘",
                    'seo_description'=>"U点房为您提供{$buildingInfo['building_name']}楼盘详情信息，{$buildingInfo['building_name']}房价走势，{$buildingInfo['building_name']}户型图，{$buildingInfo['building_name']}周边配套，了解{$buildingInfo['building_name']}楼盘信息，就上U点房。",
                );
            $this->load->model('buildings/buildingsinfo_model');
            $infoId = $this->buildingsinfo_model->insert($info_data);

        }
        return ['id'=>$returnId, 'code'=>$code];
    }
}